//
//  HTTPClient+SearchSug.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2016/11/14.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "CLHTTPClient+SearchSug.h"
#import "CLHTTPURLConfiguration.h"
#import "CLHTTPManager.h"
#import "CLBaiduSugResponseModel.h"
#import <TFHpple/TFHpple.h>
@implementation CLHTTPClient (SearchSug)

- (NSURLSessionDataTask *)getSugWithKeyword:(NSString *)keyword success:(CLSuccessBlock)success fail:(CLFailureBlock)fail{
    NSString *relativePath = [[CLHTTPURLConfiguration sharedInstance] baiduURLWithPath:keyword];
    
    return [self.httpManager GET:relativePath parameters:nil modelClass:[CLBaiduSugResponseModel class] success:success failure:fail];
}

- (NSURLSessionDataTask *)searchBookWithKeyword:(NSString *)keyword success:(void (^)(NSArray <CLSearchBook *> *books))success fail:(void(^)(NSError *error))fail {
//    NSString *relativePath = [[CLHTTPURLConfiguration sharedInstance] urlSearchBookWithPath:keyword];
    //https://m.qidian.com/soushu/%E7%A5%9E%E7%A7%98%E5%B0%BD%E5%A4%B4.html
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//    https://www.baidu.com/s?q1=笔趣阁&q2=神秘之劫&gpc=stf&ft=&q5=1
        NSString *url = [NSString stringWithFormat:@"https://m.qidian.com/soushu/%@.html",[keyword stringByURLEncode]];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        if (data) {
            TFHpple *doc = [[TFHpple alloc] initWithHTMLData:data];
            NSArray <TFHppleElement *>*elements = [doc searchWithXPathQuery:@"//li[@class='book-li ']"];
//            NSLog(@"elements.firstObject:%@",[doc searchWithXPathQuery:@"//*[@id='books-']/li[3]/a/div/div[2]/div[1]/span/text()"]);
            NSMutableArray *tmp = [NSMutableArray array];
            for (TFHppleElement *el in elements) {
                CLSearchBook *book = [[CLSearchBook alloc]init];
                book.title = [el firstElementSearchWithXPathQuery:@"//h2[@class='book-title']"].content.stringByTrim;;
                book.intro = [el firstElementSearchWithXPathQuery:@"//p[@class='book-desc']"].content.stringByTrim;;
                book.author = [el firstElementSearchWithXPathQuery:@"//span[@class='book-author']/text()[last()]"].content.stringByTrim;
                book.cover_image = [NSString stringWithFormat:@"https:%@",[[el firstElementSearchWithXPathQuery:@"//img[@class='book-cover']"] objectForKey:@"src"]];
                book.category = [el firstElementSearchWithXPathQuery:@"//em[@class='tag-small gray']"].content.stringByTrim;
                NSString *firstUrl = [[el firstElementSearchWithXPathQuery:@"//a[@class='book-layout']"] objectForKey:@"href"].stringByTrim;
                NSArray *paths = [firstUrl componentsSeparatedByString:@"/"];
                book.novel_book_id = [paths objectAtIndex:paths.count - 2];
                [tmp addObject:book];
                
                NSLog(@"%@:%@,%@",book.title,book.novel_book_id,book.category);
            }
            
            CLSafeMainExecuteBlock(success,tmp);
        } else {
            NSDictionary *userInfo = @{
                                       NSLocalizedDescriptionKey: NSLocalizedString(@"Could not parse JSON", @""),
                                       NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"Baidu Sug Response Error", @"")
                                       };
            CLSafeMainExecuteBlock(fail,[NSError errorWithDomain:NSURLErrorDomain code:404 userInfo:userInfo]);
        }
        
    });
    return [[NSURLSessionDataTask alloc]init];
//    return [self.httpManager get:relativePath parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *res) {
//        NSArray *books = [[res cl_dictionaryForKey:@"data"] cl_arrayForKey:@"doc_info"];
//        NSMutableArray *tmp = [NSMutableArray array];
//        for (NSDictionary *book in books) {
//            [tmp addObject:[CLSearchBook modelWithDictionary:book]];
//        }
//        CLSafeExecuteBlock(success,tmp);
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        CLSafeExecuteBlock(fail,error);
//    }];
}

@end
